<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author Cheng
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'maintenance:process:maintenanceTaskProcess:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />
    <div class="fireVeIm">
      <div class="fireImg">
        <span>
          异常图片:
        </span>
        <Image v-if="imageFire" :src="imageFire" width="100%" height="100%"></Image>
        <img v-else src="/@/assets/images/noData.png" alt="">
      </div>
      <div class="fireImg">
        <span>
          处理结果图片:
        </span>
        <Image  v-if="imageResult" :src="imageResult" width="100%" height="100%"></Image>
        <img v-else src="/@/assets/images/noData.png" alt="">
      </div>
    </div>
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        v-show="record.isCurrentStageOverdue!==true"
        bpmEntityKey="id"
        formKey="maintenance_process"
        completeText="提交"
        :completeModal="true"
        :loading="loadingRef"
        :auth="'maintenance:process:maintenanceTaskProcess:edit'"
        @validate="handleValidate"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsMaintenanceProcessMaintenanceTaskProcessForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { MaintenanceTaskProcess, maintenanceTaskProcessSave, maintenanceTaskProcessForm } from '/@/api/maintenance.process/maintenanceTaskProcess';
  import { BpmButton } from '/@/components/Bpm';
  import { officeTreeData } from '/@/api/sys/office';
  import { unitRegionListData } from '/@/api/unitmanage/unitRegion';
  import {empUserListData} from '/@/api/sys/empUser'
  import { Image } from 'ant-design-vue';
  

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('maintenance.process.maintenanceTaskProcess');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<MaintenanceTaskProcess>({
    isCurrentStageOverdue:true,
    bpm:{}
  } as MaintenanceTaskProcess);
  const loadingRef = ref(false);

  const imageFire = ref('');
  const imageResult = ref('');

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增维保任务处理流程记录表') : t('编辑维保任务处理流程记录表'),
  }));

  const inputFormSchemas: FormSchema[] = [
    // {
    //   label: t('维保任务ID'),
    //   field: 'maintenanceTaskId',
    //   component: 'Input',
    //   rules: [{ required: true }, { pattern: /^\d+$/, message: t('请输入一个正整数') }],
    //   componentProps:{
    //   }
    // },
    // {
    //   label: t('分配人ID'),
    //   field: 'assignerId',
    //   show: false,
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 255,
        
    //   },
    //   // required: true,
    // },
    {
      label: t('分配人姓名'),
      field: 'assignerId',
      fieldLabel:'assignerName',
      component: 'TreeSelect',
      show:()=>{
        return record.value.bpm.activityId === 'assign_employees'
      },
      componentProps: {
        maxlength: 255,
        api:empUserListData,
        resultField: 'list',
        // onChange:(userName,id)=>{
        //   record.value.assignerName = id 
        //   record.value.assignerId =userName 
        // },
        fieldNames:{
          label: 'userName',
          value: 'id',
        }
      },
      required: true,
    },
    // {
    //   label: t('所属企业编码'),
    //   field: 'enterpriseCode',
    //   // show: false,
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 255,
  
    //   },
    // },
    {
      label: t('所属企业名称'),
      field: 'enterpriseCode',
      fieldLabel:'enterpriseName',
      component: 'TreeSelect',
      componentProps: {
        maxlength: 255,
        api:officeTreeData,
        onChange:(officeCode)=>{
          record.value.enterpriseCode = officeCode
        },
        disabled:true
      }, 
    },
    {
      label: t('工单名称'),
      field: 'name',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled:true
        
      },
    },
    {
      label: t('地点'),
      field: 'address',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled:true
        
      },
    },
    {
      label: t('隐患描述'),
      field: 'remark',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 255,
        disabled:true
      },
    },
    {
      label: t('上报时间'),
      field: 'reportTime',
      component: 'DatePicker',
      componentProps:{
        format: 'YYYY-MM-DD HH:mm:ss',
        disabled:true
      }
    },
    // {
    //   label: t('区域ID'),
    //   field: 'regionId',
    //   component: 'Input',
    //   rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    //   componentProps: {
    //     diabled: true,
    //   }
    // },
    {
      label: t('区域名称'),
      field: 'regionName',
      component: 'TreeSelect',
      componentProps: {
        maxlength: 255,
        api:unitRegionListData,
        resultField: 'list',
        params:{

        },
        onChange:(id,name)=>{
          record.value.regionId = id
          record.value.regionName = name
        },
        disabled:true
        
      },
    },
    {
      label: t('购买方式'),
      field: 'purchaseMethod',
      component: 'Select',
      componentProps: {
        maxlength: 255,
        options: [
          { label: t('业主自购'), value: '1' },
          { label: t('维保公司代购'), value: '2' },
        ]  
      },
      show:()=>{
        return (record.value.handlingMethod==='2')&& (record.value.bpm.activityId === 'owner_communication')
      }
    },
    {
      label: t('处理方式'),
      field: 'handlingMethod',
      component: 'Select',
      show:()=>{
        return record.value.bpm.activityId === 'handling_method'
      },
      componentProps: {
        maxlength: 255,
        options:[
          { label: t('购买材料'), value: '2' },
          { label: t('直接处理'), value: '1' },
        ],
        
      },
    },
    {
      label: t('是否存在超期'),
      field: 'isOverdue',
      component: 'Input',
      componentProps: {
        maxlength: 10,
        disabled:true
        
      },
    },
    {
      label: t('当前环节是否超期'),
      field: 'isCurrentStageOverdue',
      component: 'Input',
      componentProps: {
        maxlength: 10,
        disabled:true
      },
    },
    {
      label: t('超期提示内容'),
      field: 'overdueMessage',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 255,
        disabled:true
        
      },
    },
 
    {
      label: t('当前环节延期时间'),
      field: 'currentStageExtensionDuration',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled:true
        
      },
    },
    {
      label: t('创建时间'),
      field: 'createTime',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm:ss',
        disabled:true
      }
    },
    {
      label: t('监督员编码'),
      field: 'supervisorCode',
      show: false,
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled:true
        
      },
    },
    {
      label: t('监督员姓名'),
      field: 'supervisorName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled:true
        
      },
    },
    // {
    //   label: t('异常图片'),
    //   field: 'dataMap',
    //   component: 'Upload',
    //   componentProps: {
    //     loadTime: computed(() => record.value.__t),
    //     bizKey: computed(() => record.value.id),
    //     bizType: 'maintenanceTaskProcess_image',
    //     fileUrl: computed(() => record.value.fileUrl),
    //     uploadType: 'image',
    //     onChange: (fileUrl) => {
    //       record.value.abnormalPic = fileUrl.maintenanceTaskProcess_image;
    //       console.log(fileUrl.maintenanceTaskProcess_image);
         
    //     }
    //   },
    //   show:()=>{
    //     return record.value.bpm.activityId === 'be_present'
    //   },
    //   colProps: { md: 24, lg: 24 },
    // },
    {
      label: t('处理结果'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'maintenanceTaskProcessResult_image',
        fileUrl: computed(() => record.value.fileUrl),
        uploadType: 'all',
        maxNumber:1,
      },
      show:()=>{
        return record.value.bpm.activityId === 'direct_processing'|| record.value.bpm.activityId === 'perform_repairs'
      },
      colProps: { md: 24, lg: 24 },
    },
    
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { md: 24, lg: 12 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await maintenanceTaskProcessForm(data);
    console.log('res', res);
    imageFire.value=res.maintenanceTaskProcess.abnormalPic;
    imageResult.value=res.maintenanceTaskProcess.resultPicUrl;
    record.value = (res.maintenanceTaskProcess || {}) as MaintenanceTaskProcess;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });



  async function handleValidate(_event: any, formData: any) {
    try {
      let data = await validate();
      data={
        ...data,
        resultPicUrl:(data.dataMap.maintenanceTaskProcessResult_imageUrl != null) ? (data.dataMap.maintenanceTaskProcessResult_imageUrl.split('?')[0]) : record.value.resultPicUrl,
        resultPicId:(data.dataMap.maintenanceTaskProcessResult_image != null) ? (data.dataMap.maintenanceTaskProcessResult_image.split('?')[0]) : record.value.resultPicId
      }
      formData(true, data); // 将表单数据传递给 BpmButton
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
    }
  }

  async function handleSubmit(event: any) {
    try {
      loadingRef.value = true;
      const data = event?.formData || (await validate()); // 接受 BpmButton 传递过来的表单数据
      data.bpm = Object.assign(data.bpm || {}, record.value.bpm); // 流程信息
      data.status = record.value.status; // 提交状态
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        tid: record.value.tid,
        enterpriseCode: record.value.enterpriseCode,
        abnormalPic:record.value.abnormalPic,
        regionId:record.value.regionId,
        assignerId:record.value.assignerId,
        assignerName:record.value.assignerName,
        
      };
      // console.log('submit', params, data, record);
      console.log('abnormalPic',params.abnormalPic)
      const res = await maintenanceTaskProcessSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>

<style scoped lang="less">
.fireVeIm{
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-bottom: 5%;
}
.fireImg {
  width: 20%;
  height: 200px;
  // margin-left: -70%;
}
</style>